import 'package:flutter/material.dart';
import 'package:flutter_study/util/log.dart';
import 'my_countdown.dart';

class MyCountdownRoute extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyCountdownRouteState();
}

class MyCountdownRouteState extends State<MyCountdownRoute> {
  final GlobalKey<MyCountdownState> _myCountdownKey = GlobalKey();  // 注意需要将 key 绑定到对应的控件上
  bool _startBtnVisible = true;
  bool _cancelBtnVisible = false;

  @override
  Widget build(BuildContext context) {

    return SafeArea(
      child: Scaffold(
        body: Column(
          children: [
            MyCountdown(_myCountdownKey, 1),  // 倒计时文本
            Visibility(
              visible: _startBtnVisible,
              child: ElevatedButton( // 开始按钮
                onPressed: (){
                  _myCountdownKey.currentState?.start();
                  _myCountdownKey.currentState?.finishCallback((){  // 倒计时结束
                    Log.i("倒计时结束");
                  });
                  setState(() {
                    _startBtnVisible = false;
                    _cancelBtnVisible = true;
                  });
                },
                child: Text("Start"),
              ),
            ),
            Visibility(
              visible: _cancelBtnVisible,
              child: ElevatedButton( // 取消按钮
                onPressed: (){
                  _myCountdownKey.currentState?.cancel();
                  setState(() {
                    _startBtnVisible = true;
                    _cancelBtnVisible = false;
                  });
                },
                child: Text("Cancel"),
              ),
            ),
          ],
        ),
      ),
    );
  }
}